package com.demo2do.boyle.client.web.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.demo2do.boyle.client.Constant;
import com.demo2do.boyle.client.handler.CookieHandler;
import com.demo2do.boyle.client.handler.OpenIdAuthHandler;
import com.demo2do.boyle.common.entity.customer.Customer;

/**
 * @author Wilson
 */
public class AuthenticateByOpenIdInterceptor extends HandlerInterceptorAdapter {

    private static final Logger logger = LoggerFactory.getLogger(AuthenticateByOpenIdInterceptor.class);

    @Autowired
    private OpenIdAuthHandler openIdAuthHandler;

    @Autowired
    private CookieHandler cookieHandler;
    
    private List<String> excludeUrls;

	public List<String> getExcludeUrls() {
		return excludeUrls;
	}

	public void setExcludeUrls(List<String> excludeUrls) {
		this.excludeUrls = excludeUrls;
	}

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    	String requestUri = request.getRequestURI();
		String contextPath = request.getContextPath();
		String url = requestUri.substring(contextPath.length());
		logger.debug(url);
    	if (excludeUrls.contains(url)) {
			return true;
		} else {
			
			// get openId from cookie
	        String openId = cookieHandler.getCookie(Constant.COOKIE_OPEN_ID, request);

	        if(openId != null) {

	            Customer customer = openIdAuthHandler.authenticate(openId);

	            if(customer != null) { // bypass if customer is not null
	                logger.info("customer successfully authenticated by openid");
	                return true;
	            }

	            logger.info("URL[" + request.getRequestURI() + "]" + "customer not found by openid, redirect to login");

	        } else {

	            logger.info("URL[" + request.getRequestURI() + "]" + "openid not found, redirect to login");
	        }
	        
		}

        request.getRequestDispatcher("/authenticate-failure").forward(request, response);

        return false;

    }

}
